﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Windows.Forms;

namespace TCECTool
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.CreateRequestBody(this.textBox1.Text);
        }

        //生成一个请求
        void CreateRequestBody(string requestParameter)
        {
            string operatorID = this.textBoxoperatorID.Text.Trim();
            string key = this.textBoxKey.Text.Trim();
            string vector = this.textBoxKeyVector.Text.Trim();
            string timeStamp = DateTime.Now.ToString("yyyyMMddHHmmss");
            string seq = this.textBoxSeq.Text.Trim();

            //string requestParameter = string.Format("\"OperatorID\":\"{0}\",\"OperatorSecret\":\"{1}\"", operatorID, key);
            //requestParameter = "{" + requestParameter + "}";

            //参数加密
            string ciphertext = AESUtil.AESEncrypt(requestParameter, key, vector);

            //生成签名
            string data = string.Format("{0}{1}{2}{3}", operatorID, ciphertext, timeStamp, seq);
            string sign = AESUtil.GetSign(this.txtSigSecret.Text.Trim(), data);

            string requestBody = string.Format("	\"TimeStamp\": \"{0}\"," +
                                    "	\"Sig\": \"{1}\"," +
                                    "	\"Data\": \"{2}\"," +
                                    "	\"OperatorID\": \"{3}\"," +
                                    "	\"Seq\": \"{4}\"",
                                    timeStamp,
                                    sign,
                                    ciphertext,
                                    operatorID,
                                    seq);
            requestBody = "{" + requestBody + "}";
            this.textBox2.Text = JObject.Parse(requestBody).ToString(Formatting.Indented);
        }

        private void buttonJiema_Click(object sender, EventArgs e)
        {
            try
            {
                var js = JObject.Parse(this.textBox1.Text);
                var data = (string)js["Data"];
                js = JObject.Parse(AESUtil.AESDecrypt(data, this.textBoxKey.Text.Trim(), this.textBoxKeyVector.Text.Trim()));
                this.textBox2.Text = js.ToString();
            }
            catch (Exception ex)
            {
                this.textBox2.Text = ex.Message;
            }
        }
    }
}
